#include "tinyos.h"

static LIST_HEAD(delay_task_list);

void task_wait(task_t *task, u32 delay)
{
    u32 status;
    
    status = task_enter_critical();
    task->delay_tick = delay;
    task_sched_unready(task);
    task->state |= TINYOS_TASK_STATE_DELAYED;
    list_add_tail(&task->entry, &delay_task_list);
    task_exit_critical(status);
    task_schedule();
}

void task_delay(u32 delay)
{
    task_wait(cur_task, delay);
}

void task_systick_handle(void)
{
    struct list_head *pos, *next;
    task_t *task;
        
    list_for_each_safe(pos, next, &delay_task_list) {
        task = list_entry(pos, task_t, entry);
        if (task->delay_tick > 0) {
            task->delay_tick--;
        }   
        if (task->delay_tick == 0) {
            task_wakeup(task);
        }        
    }
    if ((cur_task->slice > 0) && (--cur_task->slice == 0)) {
        cur_task->slice = TINYOS_SLICE_MAX;
        task_sched_ready(cur_task);
    }
    task_schedule();
}
